package com.justgame.project.mq.consumer.auth;

import com.justgame.mq.client.constant.SystemQueueConstant;
import com.justgame.project.cloud.base.abs.AbstractSmsHandler;
import com.justgame.project.cloud.common.util.MapBuilder;
import com.justgame.project.cloud.common.util.RabbitHelper;
import com.justgame.project.cloud.common.util.RandomStringUtil;
import com.justgame.project.cloud.common.util.RedisUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SmsConsumer extends RabbitHelper {

    @Autowired
    private AbstractSmsHandler authPhoneAbstractSmsHandler;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 处理用户登陆后续
     */
    @RabbitHandler
    @RabbitListener(queues = SystemQueueConstant.SMS)
    public void processSms(Channel channel, Message message) throws IOException {
        try {
            String phoneNumber = new String(message.getBody()).replaceAll("\"","");
            log.info(phoneNumber);
            String code = RandomStringUtil.Number(4);
            boolean success = authPhoneAbstractSmsHandler.handle(phoneNumber,new String[]{code});
            redisUtils.set(phoneNumber,code,5L, TimeUnit.MINUTES);
            execute(message);
        } catch (Exception e) {
            e.printStackTrace();
            receive(message,e);
        } finally {
            // ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
